package com.taobao.ic.ticket.image;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.taobao.ic.ticket.util.HttpUtils;
import com.taobao.ic.ticket.util.TrainDataUtils;

public class ImageDemo {
	private static OCR ocr = new OCR();
	public static File handleImage(String FileName) throws IOException {
		File file = new File(FileName);
		return handleImage(file);
	}

	public static File handleImage(File file) throws IOException {
		BufferedImage image = ImageIO.read(file);
		image = grayImage(image);
		image = binaryImage(image);
		ImageIO.write(image, "jpg",file);
		return file;
	}
	public static String getTextFromImage(File file,String imageFormat) throws Exception{
		handleImage(file);
		return ocr.recognizeText(file,imageFormat).trim();
	}
	private static BufferedImage binaryImage(BufferedImage image) throws IOException {
		int width = image.getWidth();
		int height = image.getHeight();
		BufferedImage grayImage = new BufferedImage(width, height,
				BufferedImage.TYPE_BYTE_BINARY);
		for (int i = 0; i < width; i++) {
			for (int j = 0; j < height; j++) {
				int rgb = image.getRGB(i, j);
				grayImage.setRGB(i, j, rgb);
			}
		}
		return grayImage;

	}

	private static BufferedImage grayImage(BufferedImage image) throws IOException {
		int width = image.getWidth();
		int height = image.getHeight();
		BufferedImage grayImage = new BufferedImage(width, height,
				BufferedImage.TYPE_BYTE_GRAY);
		for (int i = 0; i < width; i++) {
			for (int j = 0; j < height; j++) {
				int rgb = image.getRGB(i, j);
				grayImage.setRGB(i, j, rgb);
			}
		}
		return grayImage;
	}

	public static void main(String[] args) throws Exception {
		for(int x=0;x<20;x++){
		int count = 0 ;
		long cun = System.currentTimeMillis();
		while  (count<10){ 
			File file = HttpUtils.doGetCheckFile(TrainDataUtils.logCodeUrd, TrainDataUtils.saveLoginCodePath);
//			System.out.println(getTextFromImage(file));
			if(getTextFromImage(file ,"jpg").trim().length()==4){
				count ++;
			}
		}
		System.out.println((float)(System.currentTimeMillis()-cun)/1000);
		}
		}

}